package com.gopay.bis.service.bank.impl.expay;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.TransUtil;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.BankOrderManager;
import com.gopay.bis.manager.bank.expay.CmbcAdPayManager;
import com.gopay.bis.manager.bank.expay.YeePayExPayManager;
import com.gopay.bis.service.bank.sms.SmsSupportController;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.CmbcConstants;
import com.gopay.common.constants.bank.YeePayConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.ExPayBaseMessage;
import com.gopay.common.domain.bank.cmbc.expay.CmbcExPayMessage;
import com.gopay.common.domain.bank.yeepay.expay.YeePayExPayMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ExPayInteractRemoteService;

/**
 * 易宝快捷支付接口
 * 
 * @author zhengxue
 * 
 */
public class YeePayExPayServiceImpl implements ExPayInteractRemoteService {
	@Resource(name = "yeePayExPayManager")
	private YeePayExPayManager yeePayExPayManager;
	@Resource(name = "cmbcAdPayManager")
    private CmbcAdPayManager cmbcAdPayManager;
	// 短信验证码处理类
	public SmsSupportController smsController;
	@Resource(name = "bankOrderManager")
    private BankOrderManager bankOrderManager;

    /**
     * 是否需要输入cvv2
     */
    public Result queryCvn(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        YeePayExPayMessage message = new YeePayExPayMessage();
        BeanUtils.copyProperties(baseMsg, message);
        try {
            message = (YeePayExPayMessage) yeePayExPayManager.queryCvn(message);
            String errorCode = message.getErrorcode();
            if (errorCode == null || "".equals(errorCode)) {
                // 查询绑卡信息成功
                result.setModel("flag", true);
                result.setModel("isQueryCVN", message.getIsQueryCVN());
            } else {
                // 查询绑卡信息或验签失败
                result.setModel("flag", false);
                result.setModel("retMsg", message.getErrormsg());
            }
            result.setSuccess(true);
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6081);
        }
        return result;
    }

	/**
	 * 认证请求  易宝没有鉴权业务，所以调用民生代扣的鉴权接口
	 */
	public Result certification(ExPayBaseMessage baseMsg) {
	    Result result = new Result(false);
        CmbcExPayMessage message = new CmbcExPayMessage();
        BeanUtils.copyProperties(baseMsg, message);
        try {
            message = (CmbcExPayMessage) cmbcAdPayManager.certification(message);
            if (message.isFlag() && CmbcConstants.RESP_TYPE_SUCCESS.equals(message.getRetType())
                    && CmbcConstants.VALIDATE_STATUS_SUCCESS.equals(message.getValidStatus())) {
                // 代扣接口认证成功
                result.setModel("flag", true);
                result.setModel("retMsg", message.getRetMsg());
            } else {
                result.setModel("flag", false);
                result.setModel("retMsg", message.getRetMsg());
            }
            result.setSuccess(true);
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6076);
        }
        return result;
	}

	/**
	 * 发送短信验证码
	 */
	public Result sendSms(ExPayBaseMessage baseMsg) {
		Result result = new Result(false);
		YeePayExPayMessage message = new YeePayExPayMessage();
		BeanUtils.copyProperties(baseMsg, message);
		try {
		    Map<String, String> smsRes = smsController.sendSMS(message);
            if (ProcCodeConstants.PROC_CODE_100E6102.equals(smsRes.get("resCode"))) {
                // 短信发送成功
                result.setModel("flag", true);
            } else {
                // 短信发送失败
                result.setModel("flag", false);
            }
            result.setModel("sendCount", smsRes.get("sendCount"));
            result.setModel("retMsg", smsRes.get("retMsg"));
            result.setModel("resCode", smsRes.get("resCode"));
            result.setResultCode(smsRes.get("resCode"));
            result.setSuccess(true);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6077);
		}
		return result;
	}

	/**
	 * 校验短信
	 */
	public Result checkSms(ExPayBaseMessage baseMsg) {
		Result result = new Result(false);
		YeePayExPayMessage message = new YeePayExPayMessage();
		BeanUtils.copyProperties(baseMsg, message);
		try {
		    Map<String, String> smsRes = smsController.checkSMS(message);
            if (ProcCodeConstants.PROC_CODE_100E6091.equals(smsRes.get("resCode"))) {
                // 验证通过
                result.setModel("flag", true);               
            } else {
                // 验证失败
                result.setModel("flag", false);
                if(!ProcCodeConstants.PROC_CODE_100E6099.equals(smsRes.get("resCode"))){
                    Map<String, String> freezeRes = smsController.freezeCard(message);
                    if(freezeRes != null)
                        smsRes = freezeRes;
                }
            }
            result.setModel("failCount", smsRes.get("failCount"));
            result.setModel("retMsg", smsRes.get("retMsg"));
            result.setModel("resCode", smsRes.get("resCode"));
            result.setResultCode(smsRes.get("resCode"));
            result.setSuccess(true);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6078);
		}
		return result;
	}
	
	/**
	 * 确认支付
	 */
	public Result payment(ExPayBaseMessage baseMsg) {
		Result result = new Result(false);
		baseMsg.setBankOrderId("YE" + TransUtil.processOrderIdTo14Digit(baseMsg.getOrderId()));
		YeePayExPayMessage message = new YeePayExPayMessage();
		BeanUtils.copyProperties(baseMsg, message);
		try {
			message = (YeePayExPayMessage) yeePayExPayManager.payment(message);
			String errorCode = message.getErrorcode();
			if (errorCode == null || "".equals(errorCode)) {
				// 提交支付请求成功
				result.setModel("flag", true);
			} else {
				// 提交支付请求或验签失败
				result.setModel("flag", false);
				result.setModel("retMsg", message.getErrormsg());
			}
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6057);
		}
		return result;
	}
	
	/**
	 * 易宝回调通知处理
	 */
	public Result verify(ExPayBaseMessage baseMsg) {
		Result result = new Result(false);
		YeePayExPayMessage message = new YeePayExPayMessage();
		BeanUtils.copyProperties(baseMsg, message);
		try {
			YeePayExPayMessage yeePayMessage = (YeePayExPayMessage) yeePayExPayManager.verify(message);
			BankOrder bankOrder = null;
            bankOrder = bankOrderManager.getBankOrderById(yeePayMessage.getBankOrderId());
			yeePayMessage.setOrderId(bankOrder.getOrderId());
			result.setModel("res", yeePayMessage);
			result.setDefaultModel(yeePayMessage.isFlag());
			Map<String, String> param = new HashMap<String, String>();
			if (yeePayMessage.isFlag()
					&& YeePayConstants.YEEPAY_EXPAY_PAYMENT_SUCCESS.equals(yeePayMessage.getStatus())) {
				param.put("orderId", yeePayMessage.getOrderId());
				param.put("amt", formatAmt(yeePayMessage.getAmount().toString()));
				param.put("cardType", "Unknown");
				param.put("notifyNum", "1");
				param.put("payStatus", "00");
				param.put("retCode", "00");
				param.put("retMsg", "验签成功");
				param.put("signData", message.getSignMessage());
				param.put("isFront", String.valueOf(baseMsg.isFront()));
				result.setModel("isNotifyCashier", param);
				result.setSuccess(true);
				result.setOrderStatus(true);
			} else {
				// 通知后台地址该订单失败
				param.put("orderId", yeePayMessage.getOrderId());
				param.put("amt", formatAmt(yeePayMessage.getAmount().toString()));
				param.put("cardType", "Unknown");
				param.put("notifyNum", "1");
				param.put("payStatus", "01");
				param.put("retCode", "01");
				// 记录数据库失败信息 add by zhengxue 20170313
				param.put("retMsg", StringUtils.isEmpty(yeePayMessage.getErrormsg()) ? "交易失败" : yeePayMessage.getErrormsg());
				param.put("signData", message.getSignMessage());
				param.put("isFront", String.valueOf(baseMsg.isFront()));
				result.setModel("isNotifyCashier", param);
				result.setSuccess(true);
				result.setOrderStatus(false);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;
	}
	
	@Override
	public Result queryOrder(ExPayBaseMessage baseMsg) {
		Result result = new Result(false);
		YeePayExPayMessage message = new YeePayExPayMessage();
		BeanUtils.copyProperties(baseMsg, message);
		try {
			message = (YeePayExPayMessage) yeePayExPayManager.queryOrder(message);
			result.setDefaultModel(message);
			result.setSuccess(true);
			if(BisPayCheckUtils.checkExternalOrderID(baseMsg.getOrderId())){
				Map<String, String> param = new HashMap<String, String>();
				String amount = baseMsg.getAmount().toString();
				param.put("orderId", baseMsg.getOrderId());
				param.put("amount", amount);
				if (message == null) {
					// 查询结果为空
					param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
					param.put("returnMessage", "银行返回对账结果为空");
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
				}
				if(message.isFlag()){
					//成功处理
					if (YeePayConstants.YEEPAY_EXPAY_QUERY_SUCCESS.equals(message
							.getStatus())) {
						param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
						param.put("returnMessage", "交易成功");
					// 失败处理
					} else if (YeePayConstants.YEEPAY_EXPAY_QUERY_FAIL.equals(message
							.getStatus())) {
						param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
						param.put("returnMessage", "交易失败");
					// 处理中
					} else if (YeePayConstants.YEEPAY_EXPAY_QUERY_DEALING.equals(message
							.getStatus())) {
						param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
						param.put("returnMessage", "银行订单正在处理中");
					// 未处理
					} else if (YeePayConstants.YEEPAY_EXPAY_QUERY_UNTREATED.equals(message
							.getStatus())) {
						param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
						param.put("returnMessage", "交易失败");
					}else{
						param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
						param.put("returnMessage", "银行返回交易状态不明");
					}
				} else {
					param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					param.put("returnMessage", "银行验签失败");
				}
				result.setModel("queryResult", param);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6058);
		}
		return result;
	}
	
	protected String formatAmt(String amtStr) {
		// 增加校验功能，防止误操作
		if (amtStr.indexOf(".") > -1) {
			return amtStr;
		}

		BigDecimal amt = null;
		try {
			amt = new BigDecimal(amtStr);
		} catch (Exception e) {
			amt = new BigDecimal("0");
		}
		amt = amt.movePointLeft(2);
		return amt.toString();
	}
	
//	private String getCardType(String cardType) {
//		if (YeePayConstants.YEEPAY_EXPAY_DEBITCARD.equals(cardType)) {
//			return "DebitCard";
//		} else if (YeePayConstants.YEEPAY_EXPAY_CREDITCARD.equals(cardType)) {
//			return "CreditCard";
//		} else {
//			return "Unknown";
//		}
//	}

	@Override
	public Result sign(ExPayBaseMessage baseMsg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result treatyQuery(ExPayBaseMessage baseMsg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result cancel(ExPayBaseMessage baseMsg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result refund(ExPayBaseMessage baseMsg) {
		// TODO Auto-generated method stub
		return null;
	}

	public SmsSupportController getSmsController() {
		return smsController;
	}

	public void setSmsController(SmsSupportController smsController) {
		this.smsController = smsController;
	}

	public YeePayExPayManager getYeePayExPayManager() {
		return yeePayExPayManager;
	}

	public void setYeePayExPayManager(YeePayExPayManager yeePayExPayManager) {
		this.yeePayExPayManager = yeePayExPayManager;
	}

	public CmbcAdPayManager getCmbcAdPayManager() {
		return cmbcAdPayManager;
	}

	public void setCmbcAdPayManager(CmbcAdPayManager cmbcAdPayManager) {
		this.cmbcAdPayManager = cmbcAdPayManager;
	}

	public BankOrderManager getBankOrderManager() {
		return bankOrderManager;
	}

	public void setBankOrderManager(BankOrderManager bankOrderManager) {
		this.bankOrderManager = bankOrderManager;
	}

    @Override
    public Result queryNeedCert(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }
/*	@Override
	public Result refundQuery(ExPayBaseMessage baseMsg) {
		// TODO Auto-generated method stub
		return null;
	}*/

    @Override
    public Result refundBack(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }
}
